package algorithm;

import java.util.Scanner;

public class BinarySearch {
    Integer [] array = {0,3,5,7,9,21,34,56,78,111};

    /**
     * 创建数组
     */
    public void create(){
        //获取数组大小
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数组长度:");
        Integer length = Integer.parseInt(sc.nextLine());
        array = new Integer[length];

        //输入数组元素
        System.out.println("请输入数组元素:");
        for(int i =0;i < length;i ++){
            array[i] = sc.nextInt();
        }
    }

    public Integer binarySearch(Integer target){
        Integer left = 0;
        Integer right = array.length - 1;
        while(left < right){
            Integer mid = left + (right - left) / 2;
            if(array[mid] < target){
                left = mid + 1;
            } else{
                right = mid;
            }
        }
        if(array[left] != target){
            System.out.println("元素不存在");
            return null;
        }
        System.out.println(target + "所在的位置:" + left);
        return left;
    }
}
